package com.example.bigdemo.sercive.Impl;

import com.example.bigdemo.pojo.SNMPobject;
import com.example.bigdemo.pojo.Values;
import com.example.bigdemo.sercive.GetMessageService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.PDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Data
public class GetMessageImpl implements GetMessageService {
    Logger logger = LoggerFactory.getLogger(GetMessageImpl.class);

    @Override
    public String getMessageByIpAndOid(SNMPobject sobj) {
        String variableString = "";
        try{
            //设定CommunityTarget
            CommunityTarget myTarget = new CommunityTarget();
            //机器的地址
            Address address = GenericAddress.parse("udp:"+sobj.getIp()+"/161");
            //设定地址
            myTarget.setAddress(address);
            //设置snmp共同体
            myTarget.setCommunity(new OctetString("public"));
            //设置超时重试次数
            myTarget.setRetries(2);
            //设置超时的时间
            myTarget.setTimeout(5*60);
            //设置使用的snmp版本
            myTarget.setVersion(SnmpConstants.version2c);
            //设定采取的协议
            TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
            //调用TransportMapping中的listen()方法，启动监听进程，接收消息，由于该监听进程是守护进程，最后应调用close()方法来释放该进程
            transport.listen();
            //创建SNMP对象，用于发送请求PDU
            Snmp protocol = new Snmp(transport);
            //创建请求pdu,获取mib
            PDU request = new PDU();
            //调用的add方法绑定要查询的OID
            request.add(new VariableBinding(new OID(sobj.getOid())));
            //调用setType()方法来确定该pdu的类型
            request.setType(PDU.GET);
            //调用 send(PDU pdu,Target target)发送pdu，返回一个ResponseEvent对象
            ResponseEvent responseEvent = protocol.send(request, myTarget);
            //通过ResponseEvent对象来获得SNMP请求的应答pdu，方法：public PDU getResponse()
            PDU response=responseEvent.getResponse();
            //输出
            if(response != null){
                //通过应答pdu获得mib信息（之前绑定的OID的值），方法：VaribleBinding get(int index)
                VariableBinding vb = response.get(0);

              System.out.println(response);
                variableString = String.valueOf(vb.getVariable());
                //调用close()方法释放该进程
                transport.close();
            }

        }catch(IOException e){
            e.printStackTrace();
        }
        log.warn("Get查询结果如下");
        log.warn("查询ip");
        log.info(sobj.getIp());
        log.warn("查询oid");
        log.info(sobj.getOid());
        log.warn("具体信息");
        log.info(variableString);
        return variableString;
    }

    @Override
    public String getNextMessageByIpAndOid(SNMPobject sobj) {
        String getoid = null;
        String variableString = "";
        try{
            //设定CommunityTarget
            CommunityTarget myTarget = new CommunityTarget();
            //机器的地址
            Address address = GenericAddress.parse("udp:"+sobj.getIp()+"/161");
            //设定地址
            myTarget.setAddress(address);
            //设置snmp共同体
            myTarget.setCommunity(new OctetString("public"));
            //设置超时重试次数
            myTarget.setRetries(2);
            //设置超时的时间
            myTarget.setTimeout(5*60);
            //设置使用的snmp版本
            myTarget.setVersion(SnmpConstants.version2c);
            //设定采取的协议
            TransportMapping<UdpAddress> transport = new DefaultUdpTransportMapping();
            //调用TransportMapping中的listen()方法，启动监听进程，接收消息，由于该监听进程是守护进程，最后应调用close()方法来释放该进程
            transport.listen();
            //创建SNMP对象，用于发送请求PDU
            Snmp protocol = new Snmp(transport);
            //创建请求pdu,获取mib
            PDU request = new PDU();
            //调用的add方法绑定要查询的OID
            request.add(new VariableBinding(new OID(sobj.getOid())));
            //调用setType()方法来确定该pdu的类型
            request.setType(PDU.GETNEXT);
            //调用 send(PDU pdu,Target target)发送pdu，返回一个ResponseEvent对象
            ResponseEvent responseEvent = protocol.send(request, myTarget);
            //通过ResponseEvent对象来获得SNMP请求的应答pdu，方法：public PDU getResponse()
            PDU response=responseEvent.getResponse();
            //输出
            if(response != null){
                //通过应答pdu获得mib信息（之前绑定的OID的值），方法：VaribleBinding get(int index)
                VariableBinding vb = response.get(0);
//                System.out.println(vb);
                variableString = String.valueOf(vb.getVariable());
               getoid= String.valueOf(vb.getOid());

                log.warn("size");
                log.warn(String.valueOf(vb.getBERLength()));
                log.warn(String.valueOf(vb.getBERPayloadLength()));
                log.warn(vb.toString());
//                log.warn("2");
//                log.warn(String.valueOf(response.get(2)));
//                log.warn("3");
//                log.warn(String.valueOf(response.get(3)));
//                log.warn("4");
//                log.warn(String.valueOf(response.get(4)));

                //调用close()方法释放该进程
                transport.close();
            }

        }catch(IOException e){
            e.printStackTrace();
        }
        log.warn("GetNext查询结果如下");
        log.warn("查询ip");
        log.info(sobj.getIp());
        log.warn("查询oid");
        log.info(getoid);
        log.warn("具体信息");
        log.info(variableString);

        return variableString;
    }
    //转换中文
    public static String getChinese(String octetString){
        if(octetString == null || "".equals(octetString)
                || "null".equalsIgnoreCase(octetString)) return "";
        try{
            String[] temps = octetString.split(":");
            byte[] bs = new byte[temps.length];
            for(int i=0;i<temps.length;i++)
                bs[i] = (byte)Integer.parseInt(temps[i],16);
            return new String(bs,"GB2312");
        }catch(Exception e){
            return null;
        }
    }

    //  将16进制的时间转换成标准的时间格式
    private static String hexToDateTime(String hexString) {
        if(hexString == null || "".equals(hexString))
            return "";
        String dateTime = "";
        try {
            byte[] values = OctetString.fromHexString(hexString).getValue();
            int year, month, day, hour, minute;

            year = values[0] * 256 + 256 + values[1];
            month = values[2];
            day = values[3];
            hour = values[4];
            minute = values[5];

            char format_str[] = new char[22];
            int index = 3;
            int temp = year;
            for (; index >= 0; index--) {
                format_str[index] = (char) (48 + (temp - temp / 10 * 10));
                temp /= 10;
            }
            format_str[4] = '-';
            index = 6;
            temp = month;
            for (; index >= 5; index--) {
                format_str[index] = (char) (48 + (temp - temp / 10 * 10));
                temp /= 10;
            }
            format_str[7] = '-';
            index = 9;
            temp = day;
            for (; index >= 8; index--) {
                format_str[index] = (char) (48 + (temp - temp / 10 * 10));
                temp /= 10;
            }
            format_str[10] = ' ';
            index = 12;
            temp = hour;
            for (; index >= 11; index--) {
                format_str[index] = (char) (48 + (temp - temp / 10 * 10));
                temp /= 10;
            }
            format_str[13] = ':';
            index = 15;
            temp = minute;
            for (; index >= 14; index--) {
                format_str[index] = (char) (48 + (temp - temp / 10 * 10));
                temp /= 10;
            }
            dateTime = new String(format_str,0,format_str.length).substring(0, 16);
        } catch (Exception e) {
//LogFactory.getLog(getClass()).error(e);
        }
        return dateTime;
    }

    //获取cpu使用率
    @Override
    public Values GetCPUMessage(String ip) {
        int j =0;
        Values R = new Values();
        Map<String, String> variableString = new HashMap<String, String>();
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] oids = {"1.3.6.1.2.1.25.3.3.1.2"};
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);//创建snmp
            snmp.listen();//监听消息
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);

            }else{
                int percentage = 0;
                for(TableEvent event : list){

                    VariableBinding[] values = event.getColumns();
                    if(values != null)
                        percentage += Integer.parseInt(values[0].getVariable().toString());
                }

               variableString.put( "CPU利用率",percentage/list.size()+"%");
                R.setNum(j);
                R.setValue(variableString);
                j++;
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R;
    }

    //获取内存相关信息
    @Override
    public List<Values> GetMemoryMessage(String ip ) {
        List<Values> l = new ArrayList();
        int j =0;
        Map<String, String> variableString =null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] oids = {"1.3.6.1.2.1.25.2.3.1.2",  //type 存储单元类型
                "1.3.6.1.2.1.25.2.3.1.3",  //descr
                "1.3.6.1.2.1.25.2.3.1.4",  //unit 存储单元大小
                "1.3.6.1.2.1.25.2.3.1.5",  //size 总存储单元数
                "1.3.6.1.2.1.25.2.3.1.6"}; //used 使用存储单元数;
        String PHYSICAL_MEMORY_OID = "1.3.6.1.2.1.25.2.1.2";//物理存储
        String VIRTUAL_MEMORY_OID = "1.3.6.1.2.1.25.2.1.3"; //虚拟存储
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);//创建snmp
            snmp.listen();//监听消息
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    int unit = Integer.parseInt(values[2].getVariable().toString());//unit 存储单元大小
                    int totalSize = Integer.parseInt(values[3].getVariable().toString());//size 总存储单元数
                    int usedSize = Integer.parseInt(values[4].getVariable().toString());//used  使用存储单元数
                    String oid = values[0].getVariable().toString();
                    if (PHYSICAL_MEMORY_OID.equals(oid)){

                        variableString.put("内存类型","物理内存");
                        variableString.put("总储存单元数", String.valueOf(totalSize));
                        variableString.put("存储单元大小", String.valueOf(unit));
                        variableString.put("使用存储单元数", String.valueOf(usedSize));
                        variableString.put("物理内存大小",(long)totalSize * unit/(1024*1024*1024)+"G");
                        variableString.put("内存使用率",(long)usedSize*100/totalSize+"%");
                        R.setNum(j);
                        R.setValue(variableString);
                        l.add(R);
                        j++;

                    }else if (VIRTUAL_MEMORY_OID.equals(oid)) {
                        variableString =new HashMap<String, String>();
                        R = new Values();
                        variableString.put("内存类型","虚拟内存");
                        variableString.put("总储存单元数", String.valueOf(totalSize));
                        variableString.put("存储单元大小", String.valueOf(unit));
                        variableString.put("使用存储单元数", String.valueOf(usedSize));
                        variableString.put("物理内存大小",(long)totalSize * unit/(1024*1024*1024)+"G");
                        variableString.put("内存使用率",(long)usedSize*100/totalSize+"%");
                        R.setNum(j);
                        R.setValue(variableString);
                        l.add(R);
                        j++;
                    }
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //获取磁盘相关信息
    @Override
    public List<Values> GetDiskMessage(String ip) {
        List<Values> l = new ArrayList();
        int j = 0;
        Map<String, String> variableString = null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String DISK_OID = "1.3.6.1.2.1.25.2.1.4";
        String[] oids = {"1.3.6.1.2.1.25.2.3.1.2",  //type 存储单元类型
                "1.3.6.1.2.1.25.2.3.1.3",  //descr
                "1.3.6.1.2.1.25.2.3.1.4",  //unit 存储单元大小
                "1.3.6.1.2.1.25.2.3.1.5",  //size 总存储单元数
                "1.3.6.1.2.1.25.2.3.1.6"}; //used 使用存储单元数;
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);//创建snmp
            snmp.listen();//监听消息
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null ||!DISK_OID.equals(values[0].getVariable().toString()))
                        continue;
                    int unit = Integer.parseInt(values[2].getVariable().toString());//unit 存储单元大小
                    int totalSize = Integer.parseInt(values[3].getVariable().toString());//size 总存储单元数
                    int usedSize = Integer.parseInt(values[4].getVariable().toString());//used  使用存储单元数
                    variableString.put("磁盘信息",values[1].getVariable().toString());
                    variableString.put("总储存单元数", String.valueOf(totalSize));
                    variableString.put("存储单元大小", String.valueOf(unit));
                    variableString.put("使用存储单元数", String.valueOf(usedSize));
                    variableString.put("磁盘大小",(long)totalSize*unit/(1024*1024*1024)+"G");
                    variableString.put("磁盘使用率为",(long)usedSize*100/totalSize+"%");
                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //服务器端口集合
    @Override
    public List<Values> GetPortMessage(String ip) {
        List<Values> l = new ArrayList();
        int z =9999;
        int j =0;
        Map<String, String> variableString = null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] TCP_CONN = {"1.3.6.1.2.1.6.13.1.1", //status
                "1.3.6.1.2.1.6.13.1.3"}; //port

        String[] UDP_CONN = {"1.3.6.1.2.1.7.5.1.2"};
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
        //获取TCP 端口
            OID[] columns = new OID[TCP_CONN.length];
            for (int i = 0; i < TCP_CONN.length; i++)
                columns[i] = new OID(TCP_CONN[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(9999);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    int status = Integer.parseInt(values[0].getVariable().toString());
                    variableString.put("TCP_status", String.valueOf(status));
                    variableString.put("TCP_port",values[1].getVariable().toString());
                    R.setNum(z);
                    R.setValue(variableString);
                    z--;
                    l.add(R);
                }
            }
        //获取udp 端口
            OID[] udpcolumns = new OID[UDP_CONN.length];
            for (int i = 0; i < UDP_CONN.length; i++)
                udpcolumns[i] = new OID(UDP_CONN[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> udplist = tableUtils.getTable(target, udpcolumns, null, null);
            if(udplist.size()==1 && udplist.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
            }else{
                for(TableEvent event : udplist){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    String name = getChinese(values[0].getVariable().toString()) ;//name
                    variableString.put("UDP_port",name);
                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //服务器进程集合信息
    @Override
    public List<Values> GetProcessMessage(String ip) {
        List<Values> l = new ArrayList();
        int j =0;
        Map<String, String> variableString = null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] oids =
                {"1.3.6.1.2.1.25.4.2.1.1",  //index
                        "1.3.6.1.2.1.25.4.2.1.2",  //name
                        "1.3.6.1.2.1.25.4.2.1.4",  //run path
                        "1.3.6.1.2.1.25.4.2.1.6",  //type
                        "1.3.6.1.2.1.25.5.1.1.1",  //cpu
                        "1.3.6.1.2.1.25.5.1.1.2"}; //memory
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();

                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    String name = values[1].getVariable().toString();//name
                    String cpu = values[4].getVariable().toString();//cpu
                    String memory = values[5].getVariable().toString();//memory
                    String path = values[2].getVariable().toString();//path
                    variableString.put("name",name);
                    variableString.put("cpu",cpu);
                    variableString.put("memory",memory);
                    variableString.put("path",path);
                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //服务器系统服务集合
    @Override
    public List<Values> GetServiceMessage(String ip) {
        List<Values> l = new ArrayList();
        int j =0;
        Map<String, String> variableString = null;
        Values R = null ;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] oids =
                {"1.3.6.1.4.1.77.1.2.3.1.1"};
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    String name = values[0].getVariable().toString();//name
                    variableString.put("名称",getChinese(name));
                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //服务器接口集合
    @Override
    public List<Values> GetInterfaceMessage(String ip) {
        List<Values> l = new ArrayList();
        int z =9999;
        int j =0;
        Map<String, String> variableString = null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] IF_OIDS =
                {"1.3.6.1.2.1.2.2.1.1",  //Index
                        "1.3.6.1.2.1.2.2.1.2",  //descr
                        "1.3.6.1.2.1.2.2.1.3",  //type
                        "1.3.6.1.2.1.2.2.1.5",  //speed
                        "1.3.6.1.2.1.2.2.1.6",  //mac
                        "1.3.6.1.2.1.2.2.1.7",  //adminStatus
                        "1.3.6.1.2.1.2.2.1.8",  //operStatus

                        "1.3.6.1.2.1.2.2.1.10", //inOctets
                        "1.3.6.1.2.1.2.2.1.16", //outOctets
                        "1.3.6.1.2.1.2.2.1.14", //inError
                        "1.3.6.1.2.1.2.2.1.20", //outError
                        "1.3.6.1.2.1.2.2.1.13", //inDiscard
                        "1.3.6.1.2.1.2.2.1.19", //outDiscard
                        "1.3.6.1.2.1.2.2.1.11", //inUcastPkts
                        "1.3.6.1.2.1.2.2.1.17", //outUcastPkts
                        "1.3.6.1.2.1.2.2.1.12", //inNUcastPkts
                        "1.3.6.1.2.1.2.2.1.18"};//outNUcastPkts
        String[] IP_OIDS =
                {"1.3.6.1.2.1.4.20.1.1", //ipAdEntAddr
                        "1.3.6.1.2.1.4.20.1.2", //ipAdEntIfIndex
                        "1.3.6.1.2.1.4.20.1.3"};//ipAdEntNetMask
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }

            });
            OID[] columns = new OID[IF_OIDS.length];
            for (int i = 0; i < IF_OIDS.length; i++)
                columns[i] = new OID(IF_OIDS[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(9999);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;

                    variableString.put("interfaceIndex",values[0].getVariable().toString());
                    variableString.put("descr",values[1].getVariable().toString());
                    variableString.put("type",values[2].getVariable().toString());
                    variableString.put("speed",values[3].getVariable().toString());
                    variableString.put("mac",values[4].getVariable().toString());
                    variableString.put("adminStatus",values[5].getVariable().toString());
                    variableString.put("operStatus",values[6].getVariable().toString());
                    R.setNum(z);
                    R.setValue(variableString);
                    z--;
                    l.add(R);
                }
            }
            //获取ip
            OID[] ipcolumns = new OID[IP_OIDS.length];
            for (int i = 0; i < IP_OIDS.length; i++)
                ipcolumns[i] = new OID(IP_OIDS[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> iplist = tableUtils.getTable(target, ipcolumns, null, null);
            if(iplist.size()==1 && iplist.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : iplist){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;

                    variableString.put("ipAdEntAddr",values[0].getVariable().toString());
                    variableString.put("ipAdEntIfIndex",values[1].getVariable().toString());
                    variableString.put("ipAdEntNetMask",values[2].getVariable().toString());

                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }

    //服务器安装软件集合
    @Override
    public List<Values> GetSoftMessage(String ip) {
        List<Values> l = new ArrayList();
        int j =0;
        Map<String, String> variableString = null;
        Values R = null;
        TransportMapping transport = null ;
        Snmp snmp = null ;
        CommunityTarget target;
        String[] oids =
                {	"1.3.6.1.2.1.25.6.3.1.2",  //software
                        "1.3.6.1.2.1.25.6.3.1.4",  //type
                        "1.3.6.1.2.1.25.6.3.1.5"}; //install date
        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:"+ip+"/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }
            });
            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++)
                columns[i] = new OID(oids[i]);
            @SuppressWarnings("unchecked")
            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if(list.size()==1 && list.get(0).getColumns()==null){
                variableString.put("null"," null");
                R.setNum(0);
                R.setValue(variableString);
                l.add(R);
            }else{
                for(TableEvent event : list){
                    variableString =new HashMap<String, String>();
                    R = new Values();
                    VariableBinding[] values = event.getColumns();
                    if(values == null) continue;
                    String software = values[0].getVariable().toString();//software
                    String type = values[1].getVariable().toString();//type
                    String date = values[2].getVariable().toString();//date
                    variableString.put("软件名称",getChinese(software));
                    variableString.put("type",type);
                    variableString.put("安装时间",hexToDateTime(date.replace("'", "")));

                    R.setNum(j);
                    R.setValue(variableString);
                    j++;
                    l.add(R);
                }
            }
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                if(transport!=null)
                    transport.close();
                if(snmp!=null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return l;
    }



}
